package com.weimob.mcloud.wechatwork.customer.third;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.weimob.mcloud.wechatwork.core.adapter.enums.uc.UCSourceTypeEnum;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.passport.request.PassportAccountRequest;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.passport.response.PassPortAccountMappingRes;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.uc.request.UCInfoFindDTO;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.uc.response.UCInfoDetailResult;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.uc.response.UCInfoFindBO;
import com.weimob.mcloud.wechatwork.core.adapter.service.BcAdapterService;
import com.weimob.mcloud.wechatwork.core.adapter.service.ChannelAdapterService;
import com.weimob.mcloud.wechatwork.core.adapter.service.OneCrmAdapterService;
import com.weimob.mcloud.wechatwork.core.adapter.service.passport.PassPortAccountFetchService;
import com.weimob.mcloud.wechatwork.core.entity.privatesphere.PrivateSphere;
import com.weimob.mcloud.wechatwork.core.entity.relation.sid.SidInfo;
import com.weimob.mcloud.wechatwork.core.enums.privateSphere.PrivateSphereEncryptCorpEnum;
import com.weimob.mcloud.wechatwork.core.service.privatesphere.PrivateSphereService;
import com.weimob.mcloud.wechatwork.core.service.sid.SidInfoService;
import com.weimob.mcloud.wechatwork.core.service.sid.request.SingleSidInfoRequest;
import com.weimob.mcloud.wechatwork.customer.service.user.exception.BizException;
import com.weimob.soa.common.response.SoaResponse;
import com.weimob.soa.common.utils.SoaUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sunhanyue
 * @description 新中台外部服务代理类
 * @date 2021/10/23
 */
@Component
@Slf4j
public class NewRemoteOutServiceProxy {
    @Reference
    private BcAdapterService bcAdapterService;

    @Autowired
    private ChannelAdapterService channelAdapterService;

    @Reference
    private OneCrmAdapterService oneCrmAdapterService;

    @Reference
    private PassPortAccountFetchService passPortAccountFetchService;

    @Reference
    private PrivateSphereService privateSphereService;

    /**
     * 企微助手产品id
     */
    @Value("${aewc.productId:203}")
    private Long aewcProductId;


    /**
     * 批量查询passport信息
     * @return
     */
    public List<UCInfoDetailResult> findUserInfoByWids(Long bosId, Long piid, Long vid, String appId, List<Long> widList) {

        //uc限制一次最多查20条
        List<UCInfoDetailResult> ucInfoDetailResultList = Lists.newArrayList();
        List<List<Long>> widsList = Lists.partition(widList, 20);
        for (List<Long> wids : widsList) {
            UCInfoFindDTO ucInfoFindDTO = new UCInfoFindDTO();
            ucInfoFindDTO.setBosId(bosId);
            ucInfoFindDTO.setPiid(piid);
            ucInfoFindDTO.setVid(vid);
            ucInfoFindDTO.setWidList(wids);
            ucInfoFindDTO.setSourceType(UCSourceTypeEnum.WORK_WEIXIN_EXTERNAL_USERID);
            ucInfoFindDTO.setAppId(appId);
            UCInfoFindBO ucInfoFindBO = SoaUtil.unpack(oneCrmAdapterService.findUserInfoByWids(ucInfoFindDTO));
            if (ucInfoFindBO != null && ucInfoFindBO.getUcInfoDetailResultList() != null) {
                ucInfoDetailResultList.addAll(ucInfoFindBO.getUcInfoDetailResultList());
            }
        }
        return ucInfoDetailResultList;
    }


    public List<PassPortAccountMappingRes> getPassportAccountMappingRes(Long bosId, String appId, List<Long> widList, Integer source) {

        PassportAccountRequest request = new PassportAccountRequest();
        request.setBosId(bosId);
        request.setSource(source);
        request.setWidList(widList);
        request.setAppId(appId);

        if (null == source) {
            PrivateSphere privateSphereRequest = new PrivateSphere();
            privateSphereRequest.setBosId(bosId);
            privateSphereRequest.setProductId(aewcProductId);
            SoaResponse<PrivateSphere, Void> fetch = privateSphereService.fetch(privateSphereRequest);
            if (0L != Long.parseLong(fetch.getReturnCode()) || null == fetch.getResponseVo()) {
                log.error("查询私域失败, request:{}, response:{}", JSON.toJSONString(privateSphereRequest), JSON.toJSONString(fetch));
                return new ArrayList<>();
            }


            PrivateSphere privateSphere = fetch.getResponseVo();
            if (PrivateSphereEncryptCorpEnum.CIPHER.getCode().equals(privateSphere.getEncryptCorpId())) {
                request.setAppId(privateSphere.getCorpId());
                request.setSource(UCSourceTypeEnum.WORK_WEIXIN_EXTERNAL_USERID_SE.getValue());

            } else {
                request.setAppId(privateSphere.getCorpId());
                request.setSource(UCSourceTypeEnum.WORK_WEIXIN_EXTERNAL_USERID.getValue());
            }
        }



        SoaResponse<List<PassPortAccountMappingRes>, ?> listSoaResponse = passPortAccountFetchService.queryAccountMapping(request);
        if (0L != Long.parseLong(listSoaResponse.getReturnCode())) {
            log.error("根据wid查询externalUserId失败, request:{}, response:{}", request, JSON.toJSONString(listSoaResponse));
            return new ArrayList<>();
        }

         return listSoaResponse.getResponseVo();

    }


    public List<PassPortAccountMappingRes> getPassportAccountMappingRes(PrivateSphere privateSphere, List<Long> widList) {
        PassportAccountRequest request = new PassportAccountRequest();
        request.setBosId(privateSphere.getBosId());
        request.setWidList(widList);
        request.setAppId(privateSphere.getCorpId());
        //source判断，明文还是密文渠道
        if (PrivateSphereEncryptCorpEnum.CIPHER.getCode().equals(privateSphere.getEncryptCorpId())) {
            request.setAppId(privateSphere.getCorpId());
            request.setSource(UCSourceTypeEnum.WORK_WEIXIN_EXTERNAL_USERID_SE.getValue());
        } else {
            request.setAppId(privateSphere.getCorpId());
            request.setSource(UCSourceTypeEnum.WORK_WEIXIN_EXTERNAL_USERID.getValue());
        }

        SoaResponse<List<PassPortAccountMappingRes>, ?> listSoaResponse = passPortAccountFetchService.queryAccountMapping(request);
        if (0L != Long.parseLong(listSoaResponse.getReturnCode())) {
            log.error("根据wid查询externalUserId失败, request:{}, response:{}", request, JSON.toJSONString(listSoaResponse));
            return new ArrayList<>();
        }

        return listSoaResponse.getResponseVo();

    }


    @Reference
    private SidInfoService sidInfoService;


    /**
     * 获取sid
     *
     * @param privateSphere privateSphere
     * @param sidebarType       sidebarType
     * @return String String
     */
    public String fetchSid(PrivateSphere privateSphere, Integer sidebarType) {
        Long productInstanceId = privateSphere.getProductInstanceId();
        if (productInstanceId == null || sidebarType == null) {
            throw new BizException("productInstanceId或者sidebarType为空");
        }
        // 1.构造请求参数
        SingleSidInfoRequest request = new SingleSidInfoRequest();
        request.setPiid(productInstanceId);
        request.setStype(sidebarType);
        request.setTcode(privateSphere.getTcode());

        // 2.执行请求
        SidInfo sidInfo = SoaUtil.unpack(sidInfoService.fetch(request));
        if (sidInfo == null) {
            log.error("productInstanceId:{},sid:{}", productInstanceId, sidebarType);
            throw new BizException("未查询到此productInstanceId和type对应的sid");
        }
        return sidInfo.getSid();
    }
}
